package com.xbn.xbnmall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xbn.common.constant.AuthServerConstant;
import com.xbn.common.utils.HttpUtils;
import com.xbn.common.utils.R;
import com.xbn.xbnmall.auth.feign.MemberFeignService;
import com.xbn.common.vo.MemberRespVo;
import com.xbn.xbnmall.auth.vo.WeiboUserToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author XBN
 * @date 2020/8/12 19:29
 * @email 78742541@qq.com
 */
/*
* 处理社交登陆请求
* */
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;
    @GetMapping("/oauth2/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //根据code换取token
        HashMap<String,String> map=new HashMap<>();
        map.put("client_id","1286240387");
        map.put("client_secret","d6f2347255cc89c938ebe3a6ccddf16d");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.xbnmall.com/oauth2/weibo/success");
        map.put("code",code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token",
                "post", null, null, map
        );

        if(response.getStatusLine().getStatusCode()==200){
            //获取到了token令牌
            String json = EntityUtils.toString(response.getEntity());
            WeiboUserToken weiboUserToken = JSON.parseObject(json, WeiboUserToken.class);
                //登陆还是注册这个社交用户，社交用户用返回的uid作为标识，uid是不会改变的
            R r = memberFeignService.oauthLogin(weiboUserToken);
            if(r.getCode()==0)
            {
                MemberRespVo memberRespVo = r.getData("data", new TypeReference<MemberRespVo>() {
                });
               log.info("登陆成功："+memberRespVo.toString());
                //TODO 把用户信息加入到分布式session
                session.setAttribute(AuthServerConstant.LOGIN_USER_SESSION_KEY
                        ,memberRespVo);
                return "redirect:http://xbnmall.com";
            }else {
                return "redirect:http://xbnmall.com/login.html";
            }

        }
        else {
            return "redirect:http://xbnmall.com/login.html";
        }
    }
}
